package main

import (
	"fmt"
	"log"
	"rtps/discovery"
	"rtps/qos"
	"time"
)

func main() {
	fmt.Println("RTPS Simple Publisher-Subscriber Example")

	// 创建域参与者
	participant, err := discovery.NewParticipant(0)
	if err != nil {
		log.Fatal("Failed to create participant:", err)
	}
	defer participant.StopDiscovery()

	// 启动参与者发现
	if err := participant.StartDiscovery(); err != nil {
		log.Fatal("Failed to start discovery:", err)
	}

	// 创建端点管理器
	endpointManager := discovery.NewEndpointManager(participant)

	// 配置QoS
	qosProfile := qos.ReliableQoS()

	// 注册发布者
	writer, err := endpointManager.RegisterLocalWriter(
		"HelloWorldTopic",
		"HelloWorld",
		discovery.QoSProfile{
			Reliability: uint8(qosProfile.Reliability.Kind),
			Durability:  uint8(qosProfile.Durability.Kind),
			Deadline:    qosProfile.Deadline.Period,
		},
	)
	if err != nil {
		log.Fatal("Failed to register writer:", err)
	}

	fmt.Printf("Publisher created with GUID: %x\n", writer.GUID)

	// 注册订阅者
	reader, err := endpointManager.RegisterLocalReader(
		"HelloWorldTopic",
		"HelloWorld",
		discovery.QoSProfile{
			Reliability: uint8(qosProfile.Reliability.Kind),
			Durability:  uint8(qosProfile.Durability.Kind),
			Deadline:    qosProfile.Deadline.Period,
		},
	)
	if err != nil {
		log.Fatal("Failed to register reader:", err)
	}

	fmt.Printf("Subscriber created with GUID: %x\n", reader.GUID)

	// 等待发现完成
	fmt.Println("Waiting for discovery...")
	time.Sleep(5 * time.Second)

	// 检查发现的参与者
	participants := participant.GetDiscoveredParticipants()
	fmt.Printf("Discovered %d participants\n", len(participants))

	// 简单消息循环
	counter := 0
	ticker := time.NewTicker(2 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			counter++
			message := fmt.Sprintf("Hello World %d", counter)
			fmt.Printf("Publishing: %s\n", message)

			// 在实际实现中，这里会调用DataWriter.Write()
			// 简化示例，只打印消息
			fmt.Printf("Subscriber received: %s\n", message)
		}
	}
}
